package com.eh.erd.core.controller.api;


import com.eh.common.exception.Assert;
import com.eh.common.result.R;
import com.eh.common.result.ResponseEnum;
import com.eh.common.util.RegexValidateUtils;
import com.eh.erd.base.util.JwtUtils;
import com.eh.erd.core.pojo.entity.UserInfo;
import com.eh.erd.core.pojo.vo.LoginVo;
import com.eh.erd.core.pojo.vo.RegisterVo;
import com.eh.erd.core.pojo.vo.UserInfoVo;
import com.eh.erd.core.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户基本信息 前端控制器
 * </p>
 *
 * @author zhuyuanwei
 * @since 2021-04-29
 */
@Api(tags = "会员接口")
@RestController
@RequestMapping("/api/core/userInfo")
@Slf4j
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("注册功能")
    @PostMapping("/register")
    public R register(RegisterVo registerVo){

        Assert.notEmpty(registerVo.getMobile(),ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(registerVo.getPassword(),ResponseEnum.PASSWORD_NULL_ERROR);
        Assert.notEmpty(registerVo.getCode(),ResponseEnum.CODE_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(registerVo.getMobile()),ResponseEnum.MOBILE_ERROR);

        String code = (String) redisTemplate.opsForValue().get("erd:sms:code:" + registerVo.getMobile());
        Assert.equals(code,registerVo.getCode(), ResponseEnum.CODE_ERROR);

        userInfoService.register(registerVo);

        return R.ok().message("注册成功");
    }


    @ApiOperation("登录功能")
    @PostMapping("/login")
    public R login(LoginVo loginVo, HttpServletRequest request){
        Assert.notEmpty(loginVo.getMobile(),ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notEmpty(loginVo.getPassword(),ResponseEnum.PASSWORD_NULL_ERROR);
        String ip = request.getRemoteAddr();
        UserInfoVo userInfoVo=userInfoService.login(loginVo,ip);
        return R.ok().data("userInfo",userInfoVo);
    }

    @ApiOperation("校验令牌")
    @PostMapping("/checkToken")
    public R checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean b = JwtUtils.checkToken(token);
        if(b){
            return R.ok();
        }
        return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
    }

    @ApiOperation("校验手机号是否被注册")
    @PostMapping("/checkMobile/{mobile}")
    public Boolean checkMobile(@PathVariable String mobile){
        return  userInfoService.checkMobile(mobile);
    }


}

